package com.kexilo.system.system.controller;

import com.kexilo.core.common.annotation.Debounce;
import com.kexilo.core.common.annotation.Idempotent;
import com.kexilo.core.common.annotation.Log;
import com.kexilo.core.common.constant.UserConstants;
import com.kexilo.core.common.core.web.BaseController;
import com.kexilo.core.common.core.web.domain.R;
import com.kexilo.core.common.enums.BusinessType;
import com.kexilo.core.common.utils.SecurityUtils;
import com.kexilo.core.common.utils.StringUtils;
import com.kexilo.core.role.domain.SysMenu;
import com.kexilo.system.system.service.ISysMenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜单信息
 * 
 * @author Kexilo
 */
@RestController
@RequestMapping("/system/menu")
@Tag(name = "菜单管理", description = "菜单信息管理相关接口")
public class SysMenuController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(SysMenuController.class);
    
    @Autowired
    private ISysMenuService menuService;
    
    /**
     * 获取菜单列表
     */
    @PreAuthorize("@ss.hasPermi('system:menu:list')")
    @GetMapping("/list")
    @Operation(summary = "获取菜单列表", description = "获取菜单列表信息")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "403", description = "权限不足")
    })
    public R<List<SysMenu>> list(SysMenu menu) {
        List<SysMenu> menus = menuService.selectMenuList(menu);
        return success(menus);
    }
    
    /**
     * 根据菜单编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:menu:query')")
    @GetMapping(value = "/{menuId}")
    @Operation(summary = "获取菜单详情", description = "根据菜单ID获取菜单详细信息")
    public R<SysMenu> getInfo(@Parameter(description = "菜单ID") @PathVariable Long menuId) {
        return success(menuService.selectMenuById(menuId));
    }
    
    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    @Operation(summary = "获取菜单下拉树列表", description = "获取菜单树形结构数据")
    public R<List<Object>> treeselect(SysMenu menu) {
        List<SysMenu> menus = menuService.selectMenuList(menu);
        return success(menuService.buildMenuTreeSelect(menus));
    }
    
    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    @Operation(summary = "加载对应角色菜单列表树", description = "获取角色对应的菜单树结构")
    public R<Map<String, Object>> roleMenuTreeselect(@Parameter(description = "角色ID") @PathVariable("roleId") Long roleId) {
        List<SysMenu> menus = menuService.selectMenuList(SecurityUtils.getUserId());
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
        result.put("menus", menuService.buildMenuTreeSelect(menus));
        return success(result);
    }
    
    /**
     * 新增菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:add')")
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @Debounce(strategy = Debounce.Strategy.REQUEST_PARAMS, interval = 5, message = "请勿重复提交菜单信息")
    @Idempotent(strategy = Idempotent.Strategy.REQUEST_PARAMS, key = "#menu.menuName + ':' + #menu.parentId", timeout = 5, message = "该菜单正在处理中，请稍后再试")
    @PostMapping
    @Operation(summary = "新增菜单", description = "新增菜单信息")
    public R<Void> add(@Validated @RequestBody SysMenu menu) {
        if (!menuService.checkMenuNameUnique(menu)) {
            return error("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
            return error("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        menu.setCreateBy(SecurityUtils.getUsername());
        return toAjax(menuService.insertMenu(menu));
    }
    
    /**
     * 修改菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:edit')")
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @Debounce(strategy = Debounce.Strategy.REQUEST_PARAMS, interval = 3, message = "请勿频繁修改菜单信息")
    @Idempotent(strategy = Idempotent.Strategy.REQUEST_PARAMS, key = "#menu.menuId", timeout = 3, message = "菜单信息正在更新中，请稍后再试")
    @PutMapping
    @Operation(summary = "修改菜单", description = "修改菜单信息")
    public R<Void> edit(@Validated @RequestBody SysMenu menu) {
        if (!menuService.checkMenuNameUnique(menu)) {
            return error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
            return error("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        else if (menu.getMenuId().equals(menu.getParentId())) {
            return error("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(menuService.updateMenu(menu));
    }
    
    /**
     * 删除菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:remove')")
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @Debounce(strategy = Debounce.Strategy.USER_METHOD, interval = 5, message = "删除操作过于频繁，请稍后再试")
    @Idempotent(strategy = Idempotent.Strategy.REQUEST_PARAMS, key = "#menuId", timeout = 5, delKey = true, message = "删除操作正在进行中，请勿重复操作")
    @DeleteMapping("/{menuId}")
    @Operation(summary = "删除菜单", description = "删除菜单信息")
    public R<Void> remove(@Parameter(description = "菜单ID") @PathVariable("menuId") Long menuId) {
        if (menuService.hasChildByMenuId(menuId)) {
            return error("存在子菜单,不允许删除");
        }
        if (menuService.checkMenuExistRole(menuId)) {
            return error("菜单已分配,不允许删除");
        }
        return toAjax(menuService.deleteMenuById(menuId));
    }
    
    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("/getRouters")
    @Operation(summary = "获取路由信息", description = "获取当前用户的路由菜单信息")
    public R<List<Object>> getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return success(menuService.buildMenus(menus));
    }
}
